<template>
<el-dialog :title="title" :visible="showDialog" @close="handleCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
        ref="DeptForm"
        :model="DeptForm"
        label-width="120px"
        :rules="DeptRule"
    >
        <el-form-item label="部门名称" prop="name">
            <el-input v-model="DeptForm.name" style="width:80%" placeholder="1-50个字符"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
            <el-input
                v-model="DeptForm.code"
                style="width:80%"
                placeholder="1-50个字符"
            ></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
            <el-select
                v-model="DeptForm.manager"
                style="width:80%"
                placeholder="请选择"
                @focus="getManagerList"
            >
                <el-option
                    v-for="item in managerList"
                    :key="item.id"
                    :value="item.username"
                    :label="item.username"
                >
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
            <el-input
                v-model="DeptForm.introduce"
                style="width:80%"
                placeholder="1-300个字符"
                type="textarea"
                :rows="3"
            ></el-input>
        </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
        <!-- 列被分为24 -->
        <el-col style="display: flex; justify-content: center;">
            <el-button type="primary" size="small" @click="handleSubmit">确定</el-button>
            <el-button size="small" @click="handleCancel">取消</el-button>
        </el-col>
    </el-row>
</el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentsById, updateDepartmentsById } from '@/api/departments.js'
import { getEmployeeSimple } from '@/api/employees.js'
export default {
	props: {
		showDialog: {
			type: Boolean,
			default: false,
			required: true
		},
		/* 当前点击的节点数据 */
		NodeData: {
			type: Object
		},
		title: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			managerList: [],
			DeptForm: {
				name: '',
				code: '',
				manager: '',
				introduce: '',
				pid: '',
				id: '',
				createTime: ''

			},
			DeptRule: {
				name: [
					{ required: true, message: '部门名称不能为空', trigger: 'blur' },
					{ min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
					{ trigger: 'blur', validator: this.checkNameRepeat }// 自定义函数的形式校验
				],
				code: [
					{ required: true, message: '部门编码不能为空', trigger: 'blur' },
					{ min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
					{ trigger: 'blur', validator: this.checkCodeRepeat }
				],
				manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
				introduce: [
					{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
					{ trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }
				]
			}
		}
	},
	methods: {
		handleCancel() {
			this.$emit('update:showDialog', false)
			this.$refs.DeptForm.resetFields()
			this.DeptForm.id = null
			this.DeptForm.createTime = null
		},
		/* 检查重名 */
		async checkNameRepeat(rule, value, callback) {
			const { depts } = await getDepartments()
			let isRepeat = false
			/* 有ID，编辑模式 */
			if (this.DeptForm.id) {
				isRepeat = depts.filter(item => {
					/* 返回数据中，过滤掉id与当前表单id相同的（自身）并且 pid与当前点击的节点一致的（过滤子节点） */
					return item.id !== this.DeptForm.id && item.pid === this.NodeData.data.pid
				}).some(item => item.name === value)
				console.log(isRepeat)
			} else {
				isRepeat = depts.filter(item => {
					if (this.NodeData) {
						return item.pid === this.NodeData.data.id
					} else {
						return item.pid === ''
					}
				}).some(item => item.name === value)
			}
			isRepeat ? callback(new Error(`同层级下已有相同 ${value} 部门`)) : callback()
		},
		/* 检查Code */
		async checkCodeRepeat(rule, value, callback) {
			const val = await this.CodeInput(value)
			const { depts } = await getDepartments()
			let isRepeat = false
			/* 有ID，编辑模式 */
			if (this.DeptForm.id) {
				isRepeat = depts.filter(item => item.id !== this.DeptForm.id)
					.some(item => item.code === val && val)
			} else {
				isRepeat = depts.some(item => item.code === val && val) // 这里加一个 val不为空 因为我们的部门有可能没有code
			}
			isRepeat ? callback(new Error(`组织架构中已经有部门使用${val}编码`)) : callback()
		},
		/* Code转大写 */
		CodeInput(val) {
			val = val.toUpperCase()
			this.DeptForm.code = this.DeptForm.code.toUpperCase()
			return val
		},
		/* 获取负责人列表 */
		async getManagerList() {
			const res = await getEmployeeSimple()
			this.managerList = res
		},
		// 获取部门详情
		async getDepartDetail(id) {
		    this.DeptForm = await getDepartmentsById(id)
		  },
		 handleSubmit() {
			this.$refs.DeptForm.validate(async isOK => {
			        if (isOK) {
					// 表示可以提交了
					/* 有ID，编辑状态 */
					if (this.DeptForm.id) {
						await updateDepartmentsById(this.DeptForm.id, this.DeptForm)
						console.log('编辑完成')
					} else {
						/* 无ID，新增状态 */
						this.DeptForm.pid = this.NodeData ? this.NodeData.data.id : ''
						await addDepartments(this.DeptForm)
						console.log('新增完成')
					}
					this.$emit('refresh')
					this.$emit('update:showDialog', false)
			        }
			      })
		}
	}


}
</script>

<style>
</style>
